# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

import datetime
from coin.exchange.base.kr_rest.currency import NormCurrency, NativeCurrency
from coin.exchange.base.kr_rest.currency_constants import (
    BCHABC_BCHSV_FORK_TIME,
    BCHA_BCHN_FORK_TIME)
from coin.exchange.binance.kr_rest.constants import (
    currency_list,
    quote_currency_list)


# On 20191128, Binance BCHABC native symbol changeed, BCHABC -> BCH.
_BCHABC_RENAME_TIME = datetime.datetime.strptime('20191128', '%Y%m%d')


def to_native_currency(currency_str: str, current_datetime: datetime.datetime):
  native_currency_str = currency_str
  if currency_str == 'BCH':
    native_currency_str = 'BCC'
  elif currency_str == 'BCHABC' and \
       _BCHABC_RENAME_TIME <= current_datetime:
    native_currency_str = 'BCH'
  elif currency_str == 'BCHN':
    native_currency_str = "BCH"
  assert native_currency_str in currency_list + quote_currency_list, native_currency_str
  return native_currency_str


def from_native_currency(native_currency_str: str, current_datetime: datetime.datetime):
  assert native_currency_str in currency_list + quote_currency_list, native_currency_str
  currency_str = native_currency_str
  if native_currency_str == 'BCHABC':
    assert BCHABC_BCHSV_FORK_TIME <= current_datetime < _BCHABC_RENAME_TIME
  elif native_currency_str == 'BCH':
    assert _BCHABC_RENAME_TIME <= current_datetime
    if current_datetime < BCHA_BCHN_FORK_TIME:
      currency_str = 'BCHABC'
    else:
      currency_str = 'BCHN'
  elif native_currency_str == 'BCHA':
    assert BCHA_BCHN_FORK_TIME <= current_datetime
  elif native_currency_str == "BCC":
    assert current_datetime < BCHABC_BCHSV_FORK_TIME
    currency_str = "BCH"
  return currency_str


class BinanceCurrency(NativeCurrency):
  _exchange = "Binance"

  def __init__(self, currency, native_currency):
    assert currency.upper() == currency, (currency, native_currency)
    assert native_currency.upper() == native_currency, (currency, native_currency)
    assert '-' not in currency, currency
    assert '-' not in native_currency, native_currency
    super().__init__(currency, native_currency)

  @classmethod
  def FromStrCurrencyImpl(cls, currency_str, current_datetime):
    assert isinstance(currency_str, str), type(currency_str)
    return BinanceCurrency(currency_str, to_native_currency(currency_str, current_datetime))

  @classmethod
  def FromStrNativeCurrencyImpl(cls, native_currency_str, current_datetime):
    assert isinstance(native_currency_str, str), native_currency_str
    return BinanceCurrency(from_native_currency(native_currency_str, current_datetime),
                           native_currency_str)
